package com.dk.mq;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dk.constant.SeckillConstant;
import com.dk.mapper.TbSeckillOrderMapper;
import com.dk.pojo.TbSeckillCar;
import com.dk.pojo.TbSeckillOrder;
import com.dk.util.IdWorker;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@RocketMQMessageListener(consumerGroup = SeckillConstant.SECKILL_GROUP ,topic = SeckillConstant.CREATE_ORDER_TOPIC)
public class SeckillConsumer implements RocketMQListener<String> {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TbSeckillOrderMapper orderMapper;


    @Override
    public void onMessage(String message) {
        JSONObject jsonObject = JSONUtil.parseObj(message);
        Long id = Long.valueOf(jsonObject.get("id").toString());
        String username = (String) jsonObject.get("username");
        System.out.println("用户名称" + username);
        System.out.println("商品id:" + id);
        //根据商品id从redis中获取数据
        TbSeckillCar car = (TbSeckillCar) redisTemplate.boundHashOps(SeckillConstant.SECKILL_LIST).get(id);
        System.out.println(car);
        //下单
        //创建对象，并set值
        TbSeckillOrder order = new TbSeckillOrder();
        IdWorker idWorker = new IdWorker();
        long nextId = idWorker.nextId();
        order.setId(nextId);//订单id
        order.setSeckillId(car.getId()); //商品id
        order.setSellerId(car.getSellerId());//商家id
        order.setMoney(car.getCostPrice());//付款金额
        order.setUid(username);//买家用户
        order.setCreateTime(new Date());//创建时间
        order.setStatus("0");//支付状态 0为未支付

        //将订单增加order表
        orderMapper.insert(order);
        //将订单存入redis
        redisTemplate.boundValueOps(SeckillConstant.SECKILL_ORDER + username).set(nextId);


    }
}
